<template>
  <el-card shadow="never">
    <!-- 头部 -->
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }"> <i class="el-icon-house"></i> 首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品添加</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 提示 -->
    <el-alert title="增加商品"
              type="info"
              center
              effect="light"
              show-icon
              closable></el-alert>
    <!-- 步骤条 -->
    <el-steps :active="activeIndex-0"
              align-center>
      <!-- active要求是数字类型 -->
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <br><br>

    <el-form :model="addFormInfo"
             ref="addFormInfo"
             :rules="addFormRules"
             label-width="200px"
             :inline="false"
             size="normal">
      <!-- 标签页 -->
      <el-tabs tab-position="left"
               :before-leave="beforeTabChange"
               @tab-click="tabClick"
               v-model="activeIndex">
        <!-- v-model要求string -->
        <el-tab-pane name="1"
                     label="基本信息">
          <el-row>
            <el-col :span="16">
              <el-form-item label="商品名称"
                            prop="goods_name">
                <el-input v-model="addFormInfo.goods_name"
                          placeholder="请输入商品名称"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品价格"
                            prop="goods_price">
                <el-input v-model="addFormInfo.goods_price"
                          placeholder="请输入商品价格"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品数量"
                            prop="goods_number">
                <el-input v-model="addFormInfo.goods_number"
                          placeholder="请输入商品数量"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品重量"
                            prop="goods_weight">
                <el-input v-model="addFormInfo.goods_weight"
                          placeholder="请输入商品重量"
                          clearable></el-input>
              </el-form-item>
              <el-form-item label="商品分类"
                            prop="goods_cat">
                <el-cascader v-model="addFormInfo.goods_cat"
                             :options="allCateList"
                             clearable
                             :props="{
                         label:'cat_name',
                         value:'cat_id',
                         children:'children'
                       }"></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane name="2"
                     label="商品参数">
          <el-form-item v-for="(item,index) in manyList"
                        :key="index"
                        :label="item.attr_name"
                        size="normal">
            <el-checkbox-group v-model="item.check_attr_vals">
              <el-checkbox v-for="(val,idx) in item.attr_vals"
                           :key="idx"
                           :label="val"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="3"
                     label="商品属性">
          <el-form-item v-for="(item,index) in onlyList"
                        :key="index"
                        :label="item.attr_name">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="4"
                     label="商品图片">
          <!--list-type 上传控件类型  -->
          <!-- action 上传接口地址 -->
          <!-- on-preview 属性，值是函数。预览时触发 -->
          <!-- on-success 属性，值是函数。上传成功时触发 -->
          <!-- file-list 上传文件列表 -->
          <el-upload class="upload-demo"
                     action="http://localhost:8888/api/private/v1/upload"
                     :headers="{ Authorization:token }"
                     name="file"
                     :on-success="uploadSuccess"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane name="5"
                     label="商品内容">
          <!-- 富文本编辑器 -->
          <quill-editor v-model="addFormInfo.goods_introduce"
                        ref="myQuillEditor"
                        :options="editorOption">
          </quill-editor>
          <br><br><br><br>
          <el-button type="primary"
                     size="default"
                     @click="addSumbit">添加商品</el-button>

        </el-tab-pane>
      </el-tabs>
    </el-form>

  </el-card>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import _ from 'lodash'
export default {
  components: {
    quillEditor
  },
  name:'goodAdd',
  data () {
    const user = localStorage.getItem('HEIMA_SHOP_USER')
    const { token } = JSON.parse(user)
    return {
      token,
      activeIndex: '1', // 激活下标
      addFormInfo:{ // 表单数据信息
        goods_name:'手机1号',
        goods_cat:[1, 3, 6],
        goods_price:'300',
        goods_number:'10',
        goods_weight:'20',
        goods_introduce:'这是数据',
        pics:[],
        attrs:[]
      },
      addFormRules:{ // 表单验证规则
        goods_name:[{ required:true, message:'商品名称必须', trigger:'blur' }],
        goods_cat:[{ required:true, message:'商品分类必须', trigger:'blur' }],
        goods_price:[{ required:true, message:'商品价格必须', trigger:'blur' }],
        goods_number:[{ required:true, message:'商品数量必须', trigger:'blur' }],
        goods_weight:[{ required:true, message:'商品重量必须', trigger:'blur' }]
      },
      allCateList:[], // 所有分类
      onlyList:[],
      manyList:[],
      // https://quilljs.com/docs/configuration/
      editorOption:{ // 编辑器的配置
        placeholder: '请输入商品内容'
      }
    }
  },
  created () {
    this.getAllCateList()
  },
  computed: {
    // 分类ID
    cateId () {
      if (this.addFormInfo.goods_cat.length === 3) {
        return this.addFormInfo.goods_cat[2]
      } else {
        return ''
      }
    }
  },
  methods: {
    // 获取所有分类数据
    async getAllCateList () {
      const { data:res } = await this.$axios.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.allCateList = res.data
    },
    // tab切换之前
    beforeTabChange (activeName, oldActiveName) {
      // 从第1个切换走
      if (oldActiveName === '1') {
        if (this.addFormInfo.goods_cat.length !== 3) {
          this.$message.warning('请选择商品分类')
          return false // 返回false，阻止跳转切换
        }
      }
    },
    // tab切换之后
    tabClick () {
      if (this.activeIndex === '2' && !this.manyList.length) { // 商品参数
        this.getParamsList('many')
      }
      if (this.activeIndex === '3' && !this.onlyList.length) { // 商品属性
        this.getParamsList('only')
      }
    },
    // 获取静态或动态参数
    async getParamsList (sel) {
      const { data:res } = await this.$axios.get(`/categories/${this.cateId}/attributes`, {
        params:{ sel }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      if (sel === 'many') {
        res.data = res.data.map(val => {
          val.attr_vals = val.attr_vals ? val.attr_vals.split(',') : []
          val.check_attr_vals = [] // 用于存放选中内容
          return val
        })
      }
      this[sel + 'List'] = res.data
    },
    // 上传成功
    uploadSuccess (response, file, fileList) {
      if (response.meta.status !== 200) return this.$message.error(response.meta.msg)
      this.$message.success('上传成功')
      this.addFormInfo.pics.push({
        pic:response.data.tmp_path
      })
    },
    // 添加提交
    addSumbit () {
      this.$refs.addFormInfo.validate(async valid => {
        if (!valid) return false
        // 对表单数据进行一次深拷贝！这样操作数据不会影响原来的数据
        const formData = _.cloneDeep(this.addFormInfo)
        const attrs = []
        // 商品参数处理
        this.manyList.forEach(val => {
          attrs.push({
            attr_id:val.attr_id,
            attr_value:val.check_attr_vals.join(',')
          })
        })
        // 商品属性处理
        this.onlyList.forEach(val => {
          attrs.push({
            attr_id:val.attr_id,
            attr_value:val.attr_vals
          })
        })
        formData.attrs = attrs
        formData.goods_cat = formData.goods_cat.join(',')
        // 发送请求
        const { data:res } = await this.$axios.post('/goods', formData)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 跳转到列表
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped>
.quill-editor{
  height: 400px;
}
</style>
